<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
    <p>Click the start button below to begin the demonstration.</p>
    <button id="startButton" class="button">
      Start
    </button>
    <button id="getAudio" class="button">
      getAudio
    </button>
    <video id="video" width="160" height="120" autoplay controls></video><br>
    
    <div class="left">
      <h2>Audio devices:</h2>
      <ul class="deviceList" id="audioList"></ul>
    </div>
    <div class="right">
      <h2>Video devices:</h2>
      <ul class="deviceList" id="videoList"></ul>
    </div>
    <output></output>
    <script>
// UI elements
const videoElement = document.querySelector("#video");
const logElement = document.querySelector("output");
const startButton = document.querySelector("#startButton");
const getAudioButton = document.getElementById('getAudio');

function log(msg) {
  logElement.innerHTML += `${msg}<br>`;
}

getAudioButton.addEventListener('click',()=>{
  getlocalAudioLevel();
})

startButton.addEventListener(
  "click",
  () => {
    const constraints = {
      video: {
        width: 160,
        height: 120,
        frameRate: 30
      },
      audio: {
        sampleRate: 44100,
        sampleSize: 16,
        volume: 0.25
      }
    };

    navigator.mediaDevices.getUserMedia(constraints)
      .then((stream) => {
        videoElement.srcObject = stream;
        updateDeviceList();
      })
      .catch((err) => {
        log(`${err.name}: ${err.message}`);
      });
  },
  false
);

function updateDeviceList() {
  navigator.mediaDevices.enumerateDevices()
    .then((devices) => {
      audioList.innerHTML = "";
      videoList.innerHTML = "";
      devices.forEach((device) => {
        console.log('device,id', device);
        const elem = document.createElement("li");
        const [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i);
        elem.innerHTML = `<strong>${device.label}</strong> (${direction})`;
        if (type === "audio") {
          audioList.appendChild(elem);
        } else if (type === "video") {
          videoList.appendChild(elem);
        }
      });
    });
}

function  getlocalAudioLevel() {
      let videoElement = document.getElementById('video');
      // const audioContext;
      let audioContext = new (window.webkitAudioContext || window.AudioContext)()
			// 将麦克风的声音输入这个对象
			const mediaStreamSource = audioContext.createMediaStreamSource(videoElement.srcObject);
			// 创建一个音频分析对象，采样的缓冲区大小为4096，输入和输出都是单声道
			const scriptProcessor = audioContext.createScriptProcessor(4096,1,1);
			// 将该分析对象与麦克风音频进行连接
			mediaStreamSource.connect(scriptProcessor);
			// Returns an AudioDestinationNode representing the final destination of all audio in the context. It can be thought of as the audio-rendering device.
			// https://developer.mozilla.org/zh-CN/docs/Web/API/BaseAudioContext
			scriptProcessor.connect(audioContext.destination);
			// 开始处理音频
			scriptProcessor.onaudioprocess = function(e) {
				// 获得缓冲区的输入音频，转换为包含了PCM通道数据的32位浮点数组
				let buffer = e && e.inputBuffer && e.inputBuffer.getChannelData(0);
				// 获取缓冲区中最大的音量值
				let maxVal = Math.max.apply(Math, buffer);
				// maxVal ? cb(Math.round(maxVal * 100)) : cb(0);
        console.log('localaudiolevel',maxVal*100);
			}; 
}

navigator.mediaDevices.ondevicechange = (event) => {
  updateDeviceList();
};


/*
enum PermissionState {
  "granted",
  "denied",
  "prompt",
};
*/

navigator.permissions && navigator.permissions.query({ name: 'geolocation' }).then((permissionStatus) => {
  console.log(`geolocation permission state is ${permissionStatus.state}`);
  permissionStatus.onchange = () => {
    console.log(`geolocation permission state has changed to ${permissionStatus.state}`);
  };
});

navigator.permissions && navigator.permissions.query({ name: 'camera' }).then((permissionStatus) => {
  console.log(`camera permission state is ${permissionStatus.state}`);
  permissionStatus.onchange = () => {
    console.log(`camera permission state has changed to ${permissionStatus.state}`);
  };
});

navigator.permissions && navigator.permissions.query({ name: 'microphone' }).then((permissionStatus) => {
  console.log(`Microphone permission state is ${permissionStatus.state}`);
  permissionStatus.onchange = () => {
    console.log(`Microphone permission state has changed to ${permissionStatus.state}`);
  };
});



    </script>
</body>
</html>